
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { X, Brain } from "lucide-react";

interface LearningStyleAssessmentProps {
  onClose: () => void;
}

const assessmentQuestions = [
  "I learn best by watching videos or looking at images.",
  "I prefer listening to audio explanations over reading long texts.",
  "I understand new ideas better when I can talk about them with others.",
  "I like to take notes or draw diagrams while studying.",
  "I remember information better when I relate it to real-life situations.",
  "I enjoy working independently rather than in group settings.",
  "I tend to rewatch lectures or videos to review key ideas.",
  "I prefer hands-on tasks and interactive exercises.",
  "I like setting specific goals before I begin learning something new.",
  "I often reflect on what I've learned and how I learned it."
];

const scaleOptions = [
  { value: "1", label: "Strongly Disagree" },
  { value: "2", label: "Disagree" },
  { value: "3", label: "Neutral" },
  { value: "4", label: "Agree" },
  { value: "5", label: "Strongly Agree" }
];

export function LearningStyleAssessment({ onClose }: LearningStyleAssessmentProps) {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [answers, setAnswers] = useState<Record<number, string>>({});
  const [currentAnswer, setCurrentAnswer] = useState<string>("");
  const [isComplete, setIsComplete] = useState(false);
  const [profileSummary, setProfileSummary] = useState<string>("");

  const handleNext = () => {
    if (!currentAnswer) return;
    
    const updatedAnswers = { ...answers, [currentQuestion]: currentAnswer };
    setAnswers(updatedAnswers);
    
    if (currentQuestion < assessmentQuestions.length - 1) {
      setCurrentQuestion(currentQuestion + 1);
      setCurrentAnswer("");
    } else {
      generateProfileSummary(updatedAnswers);
      setIsComplete(true);
    }
  };

  const generateProfileSummary = (allAnswers: Record<number, string>) => {
    // Analyze responses to determine learning style
    const scores = {
      visual: 0,
      auditory: 0,
      social: 0,
      kinesthetic: 0,
      reflective: 0,
      independent: 0
    };

    // Question mapping to learning styles
    const questionMapping = [
      ['visual'], // Q1: videos/images
      ['auditory'], // Q2: audio explanations
      ['social'], // Q3: talking about ideas
      ['visual', 'kinesthetic'], // Q4: notes/diagrams
      ['kinesthetic'], // Q5: real-life situations
      ['independent'], // Q6: working independently
      ['visual', 'reflective'], // Q7: rewatching content
      ['kinesthetic'], // Q8: hands-on tasks
      ['reflective'], // Q9: setting goals
      ['reflective'] // Q10: reflecting on learning
    ];

    Object.entries(allAnswers).forEach(([questionIndex, answer]) => {
      const score = parseInt(answer);
      const styles = questionMapping[parseInt(questionIndex)];
      
      styles.forEach(style => {
        scores[style as keyof typeof scores] += score;
      });
    });

    // Determine primary and secondary learning styles
    const sortedStyles = Object.entries(scores)
      .sort(([,a], [,b]) => b - a)
      .map(([style]) => style);

    const primaryStyle = sortedStyles[0];
    const secondaryStyle = sortedStyles[1];

    // Generate personalized summary
    const styleDescriptions = {
      visual: "Visual",
      auditory: "Auditory", 
      social: "Social",
      kinesthetic: "Kinesthetic",
      reflective: "Reflective",
      independent: "Independent"
    };

    const strategies = {
      visual: "mind maps, infographics, and video content",
      auditory: "recorded lectures, discussions, and audio materials",
      social: "group study sessions and collaborative projects",
      kinesthetic: "hands-on activities and real-world applications",
      reflective: "goal-setting, self-assessment, and review sessions",
      independent: "solo study time and self-paced learning"
    };

    const summary = `Your learning style is primarily ${styleDescriptions[primaryStyle as keyof typeof styleDescriptions]} + ${styleDescriptions[secondaryStyle as keyof typeof styleDescriptions]}. You learn best through ${strategies[primaryStyle as keyof typeof strategies]}. Suggested strategies: ${strategies[primaryStyle as keyof typeof strategies]} and ${strategies[secondaryStyle as keyof typeof strategies]}.`;
    
    setProfileSummary(summary);
  };

  const progress = ((currentQuestion + (isComplete ? 1 : 0)) / assessmentQuestions.length) * 100;

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4">
        <div className="max-w-2xl mx-auto">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <Brain className="w-6 h-6 text-blue-600" />
                  Learning Style Assessment
                </CardTitle>
                <Button variant="ghost" size="sm" onClick={onClose}>
                  <X className="w-4 h-4" />
                </Button>
              </div>
              {!isComplete && (
                <>
                  <div className="text-sm text-gray-600">
                    Question {currentQuestion + 1} of {assessmentQuestions.length}
                  </div>
                  <Progress value={progress} className="h-2" />
                </>
              )}
            </CardHeader>

            <CardContent>
              {!isComplete ? (
                <div className="space-y-6">
                  <h3 className="text-lg font-medium">
                    {assessmentQuestions[currentQuestion]}
                  </h3>

                  <RadioGroup value={currentAnswer} onValueChange={setCurrentAnswer}>
                    {scaleOptions.map((option) => (
                      <div key={option.value} className="flex items-center space-x-3 p-3 rounded-lg border hover:bg-gray-50">
                        <RadioGroupItem value={option.value} id={option.value} />
                        <Label htmlFor={option.value} className="flex-grow cursor-pointer">
                          {option.label}
                        </Label>
                      </div>
                    ))}
                  </RadioGroup>

                  <div className="flex justify-between pt-4">
                    <Button 
                      variant="outline" 
                      onClick={() => setCurrentQuestion(Math.max(0, currentQuestion - 1))}
                      disabled={currentQuestion === 0}
                    >
                      Previous
                    </Button>
                    <Button onClick={handleNext} disabled={!currentAnswer}>
                      {currentQuestion === assessmentQuestions.length - 1 ? "Complete Assessment" : "Next"}
                    </Button>
                  </div>
                </div>
              ) : (
                <div className="text-center space-y-6">
                  <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto">
                    <Brain className="w-8 h-8 text-green-600" />
                  </div>
                  
                  <div>
                    <h3 className="text-xl font-semibold text-gray-900 mb-4">
                      Assessment Complete!
                    </h3>
                    
                    <div className="bg-blue-50 p-6 rounded-lg border border-blue-200 text-left">
                      <h4 className="font-semibold text-blue-900 mb-3">Your Learning Profile</h4>
                      <p className="text-blue-800">{profileSummary}</p>
                    </div>
                  </div>

                  <div className="flex gap-4 justify-center">
                    <Button onClick={onClose}>
                      Continue to Dashboard
                    </Button>
                    <Button variant="outline" onClick={() => {
                      setCurrentQuestion(0);
                      setAnswers({});
                      setCurrentAnswer("");
                      setIsComplete(false);
                      setProfileSummary("");
                    }}>
                      Retake Assessment
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
